package com.sicheng.lc.杂题;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/27 18:50
 */
public class 寻找最近的回文数 {
    //https://leetcode.cn/problems/find-the-closest-palindrome/
    static long[] pow = new long[19];

    static {
        pow[0] = 1;
        for (int i = 1; i <= 18; i++) {
            pow[i] = pow[i - 1] * 10;
        }
    }

    public String nearestPalindromic(String num) {
        int n = num.length();
        if (n == 1)
            return String.valueOf(Integer.parseInt(num) - 1);

        if (n == 2 && num.charAt(0) == '1' && num.charAt(1) == '1')
            return "9";
        int j = n - 1 >> 1;
        int x = 0;
        for (int i = 0; i <= j; i++) {
            x = x * 10 + (num.charAt(i) - '0');
        }
        long t = Long.parseLong(num);
        long d = Math.abs(pow[n - 1] - 1 - t);
        long res = pow[n - 1] - 1;
        for (int i = -1; i <= 1; i++) {
            long l = get(x + i, n);
            long c = Math.abs(l - t);
            if (c < d && c != 0) {
                d = c;
                res = l;
            } else if (c != 0 && c == d) {
                res = Math.min(res, l);
            }
        }

        return String.valueOf(res);
    }

    long get(int nums, int n) {
        StringBuilder last = new StringBuilder().append(nums);
        if ((n & 1) == 1) {
            StringBuilder res = new StringBuilder().append(nums / 10);
            last.append(res.reverse());
        } else {
            last.append(new StringBuilder().append(nums).reverse());
        }
        return Long.parseLong(last.toString());
    }

    public static void main(String[] args) {
        寻找最近的回文数 s = new 寻找最近的回文数();
        System.out.println(s.nearestPalindromic("9999"));
    }
}
